package com.itfreer.fileupload;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.ImageIcon;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.itfreer.file.FilePathPara;
import com.itfreer.file.FileSegmentInfo;
import com.itfreer.file.service.IBucketManageService;
import com.itfreer.file.service.IObjectDownloadService;
import com.itfreer.file.service.IObjectUploadService;
import com.itfreer.file.service.plupload.PluploadPara;
@Component(value="userPluploadService")
@Path("/userfile/plupload")
public class UserFileUpload implements BeanFactoryAware {
	@Autowired
	private IObjectUploadService objectUpload;
	@Autowired
	private IBucketManageService bucketManage;
	@Autowired
	private IObjectDownloadService objectDownload;

	@Autowired(required = false)
	private PluploadPara uploadPara;

	private PluploadPara getUploadPara() {
		if (uploadPara == null) {
			uploadPara = new PluploadPara();
		}
		return uploadPara;
	}
	@Autowired(required = true)
	private FilePathPara filePath;
	
	protected FilePathPara getPara(){
		return filePath;
	}
	
	protected String getBasePath(){
		String basepath = getPara().getFilePath();
		if(basepath==null || basepath.trim().equals("")){
			basepath = this.getClass().getClass().getResource("/").getPath();
			basepath += "upload/";
		}
		return basepath;
	}

	/**
	 * 文件上传
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	@POST
	@Path("/uploadFile")
	@Produces(javax.ws.rs.core.MediaType.TEXT_PLAIN)
	public String uploadFile(@Context HttpServletRequest request, @Context HttpServletResponse response)
			throws ServletException, IOException {

		// 1、创建一个文件上传解析器
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// threshold 极限、临界值，即硬盘缓存 1M
		factory.setSizeThreshold(102400);

		ServletFileUpload upload = new ServletFileUpload(factory);
		// 设置允许上传的最大文件大小（单位MB）
		upload.setSizeMax(getUploadPara().getMaxSize());
		upload.setHeaderEncoding("UTF-8");

		// 2、判断提交上来的数据是否是上传表单的数据
		if (!ServletFileUpload.isMultipartContent(request)) {
			return "{\"status\":false}";
		}
		
		ByteArrayOutputStream out = new ByteArrayOutputStream();

		// 3、使用ServletFileUpload解析器解析上传数据，解析结果返回的是一个List<FileItem>集合，每一个FileItem对应一个Form表单的输入项
		try {
			List<FileItem> list = upload.parseRequest(request);
			HashMap<String, Object> map = new HashMap<String, Object>();
			for (FileItem item : list) {
				if (item.isFormField()) {
					// 普通输入项
					String name = item.getFieldName();
					if ("name".equals(name)) {
						String fileName = Streams.asString(item.getInputStream(), "UTF-8");
						fileName = new String(fileName.getBytes("iso8859-1"), "UTF-8");
						map.put(name, fileName);
					} else if ("chunk".equals(name)) {
						map.put(name, Streams.asString(item.getInputStream()));
					} else if ("chunks".equals(name)) {
						map.put(name, Streams.asString(item.getInputStream()));
					}
				} else {
					// 文件内容
					map.put("content", item.getInputStream());
				}
			}

			// 此文件名是前端控件已转换后唯一的名称，非上传文件原名称
			String fileName = map.get("name").toString();
			int chunks = 0;
			if (map.containsKey("chunks")) {
				chunks = Integer.parseInt(map.get("chunks").toString());
			}
			int chunk = 0;
			if (map.containsKey("chunk")) {
				chunk = Integer.parseInt(map.get("chunk").toString());
			}

			InputStream inputStearm = (InputStream) map.get("content");
			/*ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
			byte[] buff = new byte[1024];
			int rc = 0;
			while ((rc = inputStearm.read(buff, 0, 1024)) > 0) {
				swapStream.write(buff, 0, rc);
			}*/
			
			int minx=0;
			int miny=0;
			
			int maxx=0;
			int maxy=0; 
			
			BufferedImage bi = ImageIO.read(inputStearm); 
			BufferedImage b2 =binaryImage(bi);
			Image image = (Image) b2; 
		    ImageIcon imageIcon = new ImageIcon(image); 
		    BufferedImage bufferedImage = new BufferedImage(imageIcon.getIconWidth(), imageIcon.getIconHeight(), 
		          BufferedImage.TYPE_4BYTE_ABGR); 
		    Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics(); 
		    g2D.drawImage(imageIcon.getImage(), 0, 0, imageIcon.getImageObserver()); 
		    int alpha = 0; 
		    for(int j1 = bufferedImage.getMinY(); j1 < bufferedImage.getHeight(); j1++) { 
		       for(int j2 = bufferedImage.getMinX(); j2 < bufferedImage.getWidth(); j2++) { 
		          int rgb = bufferedImage.getRGB(j2, j1); 
		  
		          int R = (rgb & 0xff0000) >> 16; 
		          int G = (rgb & 0xff00) >> 8; 
		          int B = (rgb & 0xff); 
		          
		          Color temp=new Color(rgb);
		          
		          int t_r=temp.getRed();
		          int t_g=temp.getGreen();
		          int t_b=temp.getBlue();
		          
		          double yz=t_r*0.299+t_g*0.587+t_b*0.114;

		          if(isBlackColor(bufferedImage,j2,j1)) {
		        	  //这里进行图片的裁切工作
			          if(j2<minx) {
			        	  minx=j2;
			          }
			          
			          //这里进行图片的裁切工作
			          if(j2>maxx) {
			        	  maxx=j2;
			          }
			          
			          //这里进行图片的裁切工作
			          if(j1<miny) {
			        	  miny=j1;
			          }
			          
			          //这里进行图片的裁切工作
			          if(j1>maxy) {
			        	  maxy=j1;
			          }
		          }else {
		        	  rgb = ((alpha + 1) << 24) | (rgb & 0x00ffffff); 
		          }
		          bufferedImage.setRGB(j2, j1, rgb); 
		       	} 
		   } 
		      
		      //图片裁切准备
		      //BufferedImage targetImg = bufferedImage.getSubimage(minx, miny, (maxx-minx), (maxy-miny));
		      //g2D.drawImage(targetImg, 0, 0, imageIcon.getImageObserver()); 
		      
		     //boolean flag = ImageIO.write(targetImg, "png", out);
		    boolean flag = ImageIO.write(bufferedImage, "png", out);
			byte[] content = out.toByteArray(); 
			
			// 创建存储块
			String bucketName = getUploadPara().getBucketName();
			bucketManage.createBucket(bucketName);

			// 创建存储文件的目录 ，规则为:当前日期/guid/原文件名
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			String ymd = sdf.format(new Date());
			String objectKey = ymd + "/";
			objectUpload.createDir(bucketName, objectKey);
			objectKey += fileName;

			// 配置文件大小，需和前台同步
			int segmentSize = getUploadPara().getSegmentSize();

			FileSegmentInfo fileSegmentInfo = new FileSegmentInfo();
			fileSegmentInfo.setSegmentContent(content);
			fileSegmentInfo.setSegmentIndex(chunk);
			fileSegmentInfo.setSegmentSize(segmentSize);
			fileSegmentInfo.setFileLength(segmentSize * chunks);

			if (objectUpload.uploadFile(bucketName, objectKey, fileSegmentInfo, null)) {
				return "{\"status\":true, \"bucket\":\"" + bucketName + "\",\"key\":\"" + objectKey + "\"}";
			}else {
				return "{\"status\":false}";
			}
				
		} catch (FileUploadException e) {
			e.printStackTrace();
			return "{\"status\":false}";
		}
	}
	
	/**
	 * 文件上传
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	@POST
	@Path("/appUploadFile")
	@Produces(javax.ws.rs.core.MediaType.TEXT_PLAIN)
	public String appUploadFile(@Context HttpServletRequest request, @Context HttpServletResponse response)
			throws ServletException, IOException {

		// 1、创建一个文件上传解析器
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// threshold 极限、临界值，即硬盘缓存 1M
		factory.setSizeThreshold(102400);

		ServletFileUpload upload = new ServletFileUpload(factory);
		// 设置允许上传的最大文件大小（单位MB）
		upload.setSizeMax(getUploadPara().getMaxSize());
		upload.setHeaderEncoding("UTF-8");

		// 2、判断提交上来的数据是否是上传表单的数据
		if (!ServletFileUpload.isMultipartContent(request)) {
			return "{\"status\":false}";
		}
		
		ByteArrayOutputStream out = new ByteArrayOutputStream();

		// 3、使用ServletFileUpload解析器解析上传数据，解析结果返回的是一个List<FileItem>集合，每一个FileItem对应一个Form表单的输入项
		try {
			List<FileItem> list = upload.parseRequest(request);
			HashMap<String, Object> map = new HashMap<String, Object>();
			for (FileItem item : list) {
				if (item.isFormField()) {
					// 普通输入项
					/*String name = item.getFieldName();
					if ("name".equals(name)) {
						String fileName = Streams.asString(item.getInputStream(), "UTF-8");
						fileName = new String(fileName.getBytes("iso8859-1"), "UTF-8");
						map.put(name, fileName);
					} else if ("chunk".equals(name)) {
						map.put(name, Streams.asString(item.getInputStream()));
					} else if ("chunks".equals(name)) {
						map.put(name, Streams.asString(item.getInputStream()));
					}*/
				} else {
					/*String name = item.getFieldName();
					if ("name".equals(name)) {
						String fileName = Streams.asString(item.getInputStream(), "UTF-8");
						fileName = new String(fileName.getBytes("iso8859-1"), "UTF-8");
						map.put(name, fileName);
					}*/
					map.put("name", item.getName());
					// 文件内容
					map.put("content", item.getInputStream());
				}
			}

			// 此文件名是前端控件已转换后唯一的名称，非上传文件原名称
			String fileName = map.get("name").toString();
			int chunks = 0;
			if (map.containsKey("chunks")) {
				chunks = Integer.parseInt(map.get("chunks").toString());
			}
			int chunk = 0;
			if (map.containsKey("chunk")) {
				chunk = Integer.parseInt(map.get("chunk").toString());
			}

			InputStream inputStearm = (InputStream) map.get("content");
			/*ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
			byte[] buff = new byte[1024];
			int rc = 0;
			while ((rc = inputStearm.read(buff, 0, 1024)) > 0) {
				swapStream.write(buff, 0, rc);
			}*/
			
			int minx=0;
			int miny=0;
			
			int maxx=0;
			int maxy=0; 
			
			BufferedImage bi = ImageIO.read(inputStearm); 
			BufferedImage b2 =binaryImage(bi);
			Image image = (Image) b2; 
		    ImageIcon imageIcon = new ImageIcon(image); 
		    BufferedImage bufferedImage = new BufferedImage(imageIcon.getIconWidth(), imageIcon.getIconHeight(), 
		          BufferedImage.TYPE_4BYTE_ABGR); 
		    Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics(); 
		    g2D.drawImage(imageIcon.getImage(), 0, 0, imageIcon.getImageObserver()); 
		    int alpha = 0; 
		    for(int j1 = bufferedImage.getMinY(); j1 < bufferedImage.getHeight(); j1++) { 
		       for(int j2 = bufferedImage.getMinX(); j2 < bufferedImage.getWidth(); j2++) { 
		          int rgb = bufferedImage.getRGB(j2, j1); 
		  
		          int R = (rgb & 0xff0000) >> 16; 
		          int G = (rgb & 0xff00) >> 8; 
		          int B = (rgb & 0xff); 
		          
		          Color temp=new Color(rgb);
		          
		          int t_r=temp.getRed();
		          int t_g=temp.getGreen();
		          int t_b=temp.getBlue();
		          
		          double yz=t_r*0.299+t_g*0.587+t_b*0.114;

		          if(isBlackColor(bufferedImage,j2,j1)) {
		        	  //这里进行图片的裁切工作
			          if(j2<minx) {
			        	  minx=j2;
			          }
			          
			          //这里进行图片的裁切工作
			          if(j2>maxx) {
			        	  maxx=j2;
			          }
			          
			          //这里进行图片的裁切工作
			          if(j1<miny) {
			        	  miny=j1;
			          }
			          
			          //这里进行图片的裁切工作
			          if(j1>maxy) {
			        	  maxy=j1;
			          }
		          }else {
		        	  rgb = ((alpha + 1) << 24) | (rgb & 0x00ffffff); 
		          }
		          bufferedImage.setRGB(j2, j1, rgb); 
		       	} 
		   } 
		      
		      //图片裁切准备
		      //BufferedImage targetImg = bufferedImage.getSubimage(minx, miny, (maxx-minx), (maxy-miny));
		      //g2D.drawImage(targetImg, 0, 0, imageIcon.getImageObserver()); 
		      
		     //boolean flag = ImageIO.write(targetImg, "png", out);
		    boolean flag = ImageIO.write(bufferedImage, "png", out);
			byte[] content = out.toByteArray(); 
			
			// 创建存储块
			String bucketName = getUploadPara().getBucketName();
			bucketManage.createBucket(bucketName);

			// 创建存储文件的目录 ，规则为:当前日期/guid/原文件名
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			String ymd = sdf.format(new Date());
			String objectKey = ymd + "/";
			objectUpload.createDir(bucketName, objectKey);
			objectKey += fileName;

			// 配置文件大小，需和前台同步
			int segmentSize = getUploadPara().getSegmentSize();

			FileSegmentInfo fileSegmentInfo = new FileSegmentInfo();
			fileSegmentInfo.setSegmentContent(content);
			fileSegmentInfo.setSegmentIndex(chunk);
			fileSegmentInfo.setSegmentSize(segmentSize);
			fileSegmentInfo.setFileLength(segmentSize * chunks);

			if (objectUpload.uploadFile(bucketName, objectKey, fileSegmentInfo, null)) {
				return "{\"status\":true, \"bucket\":\"" + bucketName + "\",\"key\":\"" + objectKey + "\"}";
			}else {
				return "{\"status\":false}";
			}
				
		} catch (FileUploadException e) {
			e.printStackTrace();
			return "{\"status\":false}";
		}
	}
	
	/**
	 * 移动端更新
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	@POST
	@Path("/appUpdate")
	@Produces(javax.ws.rs.core.MediaType.TEXT_PLAIN)
	public String appUpdate(@Context HttpServletRequest request, @Context HttpServletResponse response)
			throws ServletException, IOException {

		// 1、创建一个文件上传解析器
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// threshold 极限、临界值，即硬盘缓存 1M
		factory.setSizeThreshold(102400);

		ServletFileUpload upload = new ServletFileUpload(factory);
		// 设置允许上传的最大文件大小（单位MB）
		upload.setSizeMax(getUploadPara().getMaxSize());
		upload.setHeaderEncoding("UTF-8");

		// 2、判断提交上来的数据是否是上传表单的数据
		if (!ServletFileUpload.isMultipartContent(request)) {
			return "{\"status\":false}";
		}

		// 3、使用ServletFileUpload解析器解析上传数据，解析结果返回的是一个List<FileItem>集合，每一个FileItem对应一个Form表单的输入项
		try {
			List<FileItem> list = upload.parseRequest(request);
			HashMap<String, Object> map = new HashMap<String, Object>();
			for (FileItem item : list) {
				if (item.isFormField()) {
					// 普通输入项
					String name = item.getFieldName();
					if ("name".equals(name)) {
						String fileName = Streams.asString(item.getInputStream(), "UTF-8");
						fileName = new String(fileName.getBytes("iso8859-1"), "UTF-8");
						map.put(name, fileName);
					} else if ("chunk".equals(name)) {
						map.put(name, Streams.asString(item.getInputStream()));
					} else if ("chunks".equals(name)) {
						map.put(name, Streams.asString(item.getInputStream()));
					}
				} else {
					// 文件内容
					map.put("content", item.getInputStream());
				}
			}

			// 此文件名是前端控件已转换后唯一的名称，非上传文件原名称
			String fileName = "maolanoa.apk";
			int chunks = 0;
			if (map.containsKey("chunks")) {
				chunks = Integer.parseInt(map.get("chunks").toString());
			}
			int chunk = 0;
			if (map.containsKey("chunk")) {
				chunk = Integer.parseInt(map.get("chunk").toString());
			}
			InputStream is = (InputStream) map.get("content");
			wirteApp(is,fileName);
			InputStream inputStearm = new FileInputStream("../webapps/bhqoa_server/app/"+fileName);
			ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
			byte[] buff = new byte[1024];
			int rc = 0;
			while ((rc = inputStearm.read(buff, 0, 1024)) > 0) {
				swapStream.write(buff, 0, rc);
			}
			byte[] content = swapStream.toByteArray();
			
			is.close();
			inputStearm.close();
			// 创建存储块
			//String bucketName = getUploadPara().getBucketName();
			String bucketName = "app";
			bucketManage.createBucket(bucketName);

			// 创建存储文件的目录 ，规则为:当前日期/guid/原文件名
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			String ymd = sdf.format(new Date());
			String objectKey = ymd + "/";
			objectUpload.createDir(bucketName, objectKey);
			objectKey += fileName;
			
			// 配置文件大小，需和前台同步
			int segmentSize = getUploadPara().getSegmentSize();

			FileSegmentInfo fileSegmentInfo = new FileSegmentInfo();
			fileSegmentInfo.setSegmentContent(content);
			fileSegmentInfo.setSegmentIndex(chunk);
			fileSegmentInfo.setSegmentSize(segmentSize);
			fileSegmentInfo.setFileLength(segmentSize * chunks);

			if (objectUpload.uploadFile(bucketName, objectKey, fileSegmentInfo, null)) {
				return "{\"status\":true, \"bucket\":\"" + bucketName + "\",\"key\":\"" + objectKey + "\"}";
			}else {
				return "{\"status\":false}";
			}
				
		} catch (FileUploadException e) {
			e.printStackTrace();
			return "{\"status\":false}";
		}
	}
	
	//把app写入到指定目录
	public static void wirteApp(InputStream is,String fileName) throws IOException{
	    BufferedInputStream in=null;
	    BufferedOutputStream out=null;
	    in=new BufferedInputStream(is);
	    File file1 = new File("../webapps/bhqoa_server/app/");
	    if(!file1.exists()) {
	    	file1.mkdirs();
	    }
	    File file2 = new File("../webapps/bhqoa_server/app/"+fileName);
	    if(!file2.exists()) {
	    	file2.createNewFile();
	    }else {
	    	if(file2.delete()) {
	    		file2.createNewFile();
	    	}else {
	    		System.out.println("原文件删除失败！");
	    	}
	    }
	    out=new BufferedOutputStream(new FileOutputStream("../webapps/bhqoa_server/app/"+fileName));
	    int len=-1;
	    byte[] b=new byte[1024];
	    while((len=in.read(b))!=-1){
	        out.write(b,0,len);
	    }
	    out.close();
	}

	/**
	 * 下载文件
	 * 
	 * @param template
	 *            模板文件
	 * @param data
	 *            模板数据
	 */
	@GET
	@Path("/download")
	@Produces({MediaType.APPLICATION_OCTET_STREAM})
	public Response download(@QueryParam("bucket") String bucketName, 
			@QueryParam("key") String objectKey,
			@QueryParam("name") String filename) throws Exception {
		byte[] result = objectDownload.getObject(bucketName, objectKey);
		StreamingOutput stream = new StreamingOutput() {
			@Override
			public void write(OutputStream output) throws IOException, WebApplicationException {
				try {
					output.write(result);
	            } catch (Exception e) {
	                throw new WebApplicationException(e);
	            }
			}
	    };
	    return Response.ok(stream)
	    		.header("content-disposition","attachment; filename =" + new String(filename.getBytes("utf-8"), "ISO-8859-1"))
	    		.header("Cache-Control", "no-cache").build();
	}
	
	 public BufferedImage binaryImage(BufferedImage image) throws IOException{
		int width = image.getWidth();
		int height = image.getHeight();
		
		BufferedImage grayImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_BINARY);//重点，技巧在这个参数BufferedImage.TYPE_BYTE_BINARY
		for(int i= 0 ; i < width ; i++){
		    for(int j = 0 ; j < height; j++){
			int rgb = image.getRGB(i, j);
			grayImage.setRGB(i, j, rgb);
		    }
		}
		grayImage=denoise(grayImage);
		return grayImage;
    }
	 
	 public static BufferedImage denoise(BufferedImage image){
		int w = image.getWidth();  
	    int h = image.getHeight();
	    int white = new Color(255, 255, 255).getRGB();  
 
	    if(isWhite(image.getRGB(1, 0)) && isWhite(image.getRGB(0, 1)) && isWhite(image.getRGB(1, 1))){
	    	image.setRGB(0,0,white);
        }
	    if(isWhite(image.getRGB(w-2, 0)) && isWhite(image.getRGB(w-1, 1)) && isWhite(image.getRGB(w-2, 1))){
	    	image.setRGB(w-1,0,white);
        }
	    if(isWhite(image.getRGB(0, h-2)) && isWhite(image.getRGB(1, h-1)) && isWhite(image.getRGB(1, h-2))){
	    	image.setRGB(0,h-1,white);
        }
	    if(isWhite(image.getRGB(w-2, h-1)) && isWhite(image.getRGB(w-1, h-2)) && isWhite(image.getRGB(w-2, h-2))){
	    	image.setRGB(w-1,h-1,white);
        }
	    
	    for(int x = 1; x < w-1; x++){
	    	int y = 0;
	    	if(isBlack(image.getRGB(x, y))){
            	int size = 0;
                if(isWhite(image.getRGB(x-1, y))){
                	size++;
                }
                if(isWhite(image.getRGB(x+1, y))){
                	size++;
                }
                if(isWhite(image.getRGB(x, y+1))){
                	size++;
                }
                if(isWhite(image.getRGB(x-1, y+1))){
                	size++;
                }
                if(isWhite(image.getRGB(x+1, y+1))){
                	size++;
                } 
                if(size>=5){
                	image.setRGB(x,y,white);                     
                }
            }
	    }
	    for(int x = 1; x < w-1; x++){
	    	int y = h-1;
	    	if(isBlack(image.getRGB(x, y))){
            	int size = 0;
                if(isWhite(image.getRGB(x-1, y))){
                	size++;
                }
                if(isWhite(image.getRGB(x+1, y))){
                	size++;
                }
                if(isWhite(image.getRGB(x, y-1))){
                	size++;
                }
                if(isWhite(image.getRGB(x+1, y-1))){
                	size++;
                }
                if(isWhite(image.getRGB(x-1, y-1))){
                	size++;
                }
                if(size>=5){
                	image.setRGB(x,y,white);                     
                }
            }
	    }
	    
	    for(int y = 1; y < h-1; y++){
	    	int x = 0;
	    	if(isBlack(image.getRGB(x, y))){
            	int size = 0;
                if(isWhite(image.getRGB(x+1, y))){
                	size++;
                }
                if(isWhite(image.getRGB(x, y+1))){
                	size++;
                }
                if(isWhite(image.getRGB(x, y-1))){
                	size++;
                }
                if(isWhite(image.getRGB(x+1, y-1))){
                	size++;
                }
                if(isWhite(image.getRGB(x+1, y+1))){
                	size++;
                } 
                if(size>=5){
                	image.setRGB(x,y,white);                     
                }
            }
	    }
	    
	    for(int y = 1; y < h-1; y++){
	    	int x = w - 1;
	    	if(isBlack(image.getRGB(x, y))){
            	int size = 0;
            	if(isWhite(image.getRGB(x-1, y))){
                	size++;
                }
                if(isWhite(image.getRGB(x, y+1))){
                	size++;
                }
                if(isWhite(image.getRGB(x, y-1))){
                	size++;
                }
                //斜上下为空时，去掉此点
                if(isWhite(image.getRGB(x-1, y+1))){
                	size++;
                }
                if(isWhite(image.getRGB(x-1, y-1))){
                	size++;
                }
                if(size>=5){
                	image.setRGB(x,y,white);                     
                }
            }
	    }
	    
		//降噪，以1个像素点为单位
    	for(int y = 1; y < h-1; y++){
            for(int x = 1; x < w-1; x++){                   
                if(isBlack(image.getRGB(x, y))){
                	int size = 0;
                    //上下左右均为空时，去掉此点
                    if(isWhite(image.getRGB(x-1, y))){
                    	size++;
                    }
                    if(isWhite(image.getRGB(x+1, y))){
                    	size++;
                    }
                    //上下均为空时，去掉此点
                    if(isWhite(image.getRGB(x, y+1))){
                    	size++;
                    }
                    if(isWhite(image.getRGB(x, y-1))){
                    	size++;
                    }
                    //斜上下为空时，去掉此点
                    if(isWhite(image.getRGB(x-1, y+1))){
                    	size++;
                    }
                    if(isWhite(image.getRGB(x+1, y-1))){
                    	size++;
                    }
                    if(isWhite(image.getRGB(x+1, y+1))){
                    	size++;
                    } 
                    if(isWhite(image.getRGB(x-1, y-1))){
                    	size++;
                    }
                    if(size>=8){
                    	image.setRGB(x,y,white);                     
                    }
                }
            }
        }
	    
	    return image;
	}
		
	 public static boolean isBlack(int colorInt)  
     {  
         Color color = new Color(colorInt);  
         if (color.getRed() + color.getGreen() + color.getBlue() <= 300)  
         {  
             return true;  
         }  
         return false;  
     }  
	 
     public static boolean isWhite(int colorInt)  
     {  
         Color color = new Color(colorInt);  
         if (color.getRed() + color.getGreen() + color.getBlue() > 300)  
         {  
             return true;  
         }  
         return false;  
     }  
	     
     public static int isBlack(int colorInt, int whiteThreshold) {
 		final Color color = new Color(colorInt);
 		if (color.getRed() + color.getGreen() + color.getBlue() <= whiteThreshold) {
 			return 1;
 		}
 		return 0;

     }
	

	public static byte[] transferAlpha() { 
		
		int minx=0;
		int miny=0;
		
		int maxx=0;
		int maxy=0;
		  
	    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); 
	    File file = new File("D:\\print\\input\\test\\IMG_20190108_175650.jpg"); 
	    InputStream is; 
	    try { 
	      is = new FileInputStream(file); 
	      // 如果是MultipartFile类型，那么自身也有转换成流的方法：is = file.getInputStream(); 
	      BufferedImage bi = ImageIO.read(is); 
	      Image image = (Image) bi; 
	      ImageIcon imageIcon = new ImageIcon(image); 
	      BufferedImage bufferedImage = new BufferedImage(imageIcon.getIconWidth(), imageIcon.getIconHeight(), 
	          BufferedImage.TYPE_4BYTE_ABGR); 
	      Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics(); 
	      g2D.drawImage(imageIcon.getImage(), 0, 0, imageIcon.getImageObserver()); 
	      int alpha = 0; 
	      for (int j1 = bufferedImage.getMinY(); j1 < bufferedImage.getHeight(); j1++) { 
	        for (int j2 = bufferedImage.getMinX(); j2 < bufferedImage.getWidth(); j2++) { 
	          int rgb = bufferedImage.getRGB(j2, j1); 
	  
	          int R = (rgb & 0xff0000) >> 16; 
	          int G = (rgb & 0xff00) >> 8; 
	          int B = (rgb & 0xff); 
	          
	          Color temp=new Color(rgb);
	          
	          int t_r=temp.getRed();
	          int t_g=temp.getGreen();
	          int t_b=temp.getBlue();
	          
	          double yz=t_r*0.299+t_g*0.587+t_b*0.114;
	          
	          //阈值50以内都认为是黑色
	         /* if(yz<100) {
	        	//这里进行图片的裁切工作
		          if(j2<minx) {
		        	  minx=j2;
		          }
		          
		        //这里进行图片的裁切工作
		          if(j2>maxx) {
		        	  maxx=j2;
		          }
		          
		        //这里进行图片的裁切工作
		          if(j1<miny) {
		        	  miny=j1;
		          }
		          
		        //这里进行图片的裁切工作
		          if(j1>maxy) {
		        	  maxy=j1;
		          }
		          
		          //#000000
		          //rgb = ((alpha +100) << 24) | (rgb & 0x000000); 
	          }else {
	        	  rgb = ((alpha + 1) << 24) | (rgb & 0x00ffffff); 
	          }*/
	          if(isBlackColor(bufferedImage,j2,j1)) {
	        	//这里进行图片的裁切工作
		          if(j2<minx) {
		        	  minx=j2;
		          }
		          
		        //这里进行图片的裁切工作
		          if(j2>maxx) {
		        	  maxx=j2;
		          }
		          
		        //这里进行图片的裁切工作
		          if(j1<miny) {
		        	  miny=j1;
		          }
		          
		        //这里进行图片的裁切工作
		          if(j1>maxy) {
		        	  maxy=j1;
		          }
	          }else {
	        	  rgb = ((alpha + 1) << 24) | (rgb & 0x00ffffff); 
	          }
	          bufferedImage.setRGB(j2, j1, rgb); 
	          
	          
	          
	         /* if (((255 - R) < 30) && ((255 - G) < 30) && ((255 - B) < 30)) { 
	            rgb = ((alpha + 1) << 24) | (rgb & 0x00ffffff); 
	            
	          //****************图片裁切需要使用到的函数-s
	          }else {
	        	//这里进行图片的裁切工作
		          if(j2<minx) {
		        	  minx=j2;
		          }
		          
		        //这里进行图片的裁切工作
		          if(j2>maxx) {
		        	  maxx=j2;
		          }
		          
		        //这里进行图片的裁切工作
		          if(j1<miny) {
		        	  miny=j1;
		          }
		          
		        //这里进行图片的裁切工作
		          if(j1>maxy) {
		        	  maxy=j1;
		          }
	          }
	          //****************图片裁切需要使用到的函数-e
	  
	          bufferedImage.setRGB(j2, j1, rgb); */
	        } 
	      } 
	      
	      //图片裁切准备
	      BufferedImage targetImg = bufferedImage.getSubimage(minx, miny, (maxx-minx), (maxy-miny));
	      g2D.drawImage(targetImg, 0, 0, imageIcon.getImageObserver()); 
	      ImageIO.write(targetImg, "png", new File("D:\\print\\input\\test\\index3.jpg"));// 直接输出文件
	  
	      //g2D.drawImage(bufferedImage, 0, 0, imageIcon.getImageObserver()); 
	      //ImageIO.write(bufferedImage, "png", new File("D:\\print\\input\\test\\index2.jpg"));// 直接输出文件 
	    } catch (Exception e) { 
	      e.printStackTrace(); 
	    } finally { 
	  
	    } 
	    return byteArrayOutputStream.toByteArray(); 
	  } 
	
	static boolean  isBlackColor(BufferedImage bufferedImage,int x,int y) {
		
		int sz_yz=70;//设定阈值
		
		int sz_fz=7;//设定范围阈值
		
		double sz_count=0.3;//设置范围内函数
		
		int rgb = bufferedImage.getRGB(x, y); 
		Color temp=new Color(rgb);
		int t_r=temp.getRed();
        int t_g=temp.getGreen();
        int t_b=temp.getBlue();
        double temp_yz=t_r*0.299+t_g*0.587+t_b*0.114;
        
        if(temp_yz<sz_yz) {
        	if((x-sz_fz)<bufferedImage.getMinX() || (x+sz_fz)>(bufferedImage.getMinX()+bufferedImage.getWidth())) {
        		return false;
        	}
        	
        	if((y-sz_fz)<bufferedImage.getMinY() || (y+sz_fz)>(bufferedImage.getMinY()+bufferedImage.getHeight())) {
        		return false;
        	}
        	
        	int count=0;
        	
        	for(int i_x=x-sz_fz;i_x<x+sz_fz;i_x++) {
        		for(int i_y=y-sz_fz;i_y<y+sz_fz;i_y++) {
        			int rgb2 = bufferedImage.getRGB(i_x, i_y); 
        			Color temp2=new Color(rgb2);
        			int t2_r=temp2.getRed();
        	        int t2_g=temp2.getGreen();
        	        int t2_b=temp2.getBlue();
        	        double temp2_yz=t2_r*0.299+t2_g*0.587+t2_b*0.114;
        	        
        	        if(temp2_yz<sz_yz) {
        	        	 count++;
        	        }
            	}
        	}
        	
        	if(count<(sz_fz*2+1)*(sz_fz*2+1)*sz_count) {
        		return false;
        	}else {
        		return true;
        	}
        }
		
		return false;
	}
	
	protected static BeanFactory beanFactory;

	@Override
	public void setBeanFactory(BeanFactory bf) throws BeansException {
		beanFactory = bf;
	}
	
	
}
